<?php

namespace app\common\model;

use app\common\model\product\Member;
use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
        'join_date',
        'validity_date',
        'is_expires',
        'level_name',
    ];
    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getJoindateAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['jointime']) ? $data['jointime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getValidityDateAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['validitytime']) ? $data['validitytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getLevelNameAttr($value, $data)
    {
        $level = Member::get($data['leaf_level']);
        return isset($level['title']) ? $level['title'] : '';
    }
    public function getIsExpiresAttr($value, $data)
    {
        return $data['validitytime'] > time() ? false : true;
    }
    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return cdnurl($value, true);
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
    /**
     * 变更会员金叶子
     * @param int    $leaf   金叶子
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function leaf($leaf, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $leaf != 0) {
                $before = $user->gold_leaf;
                $after = $user->gold_leaf + $leaf;
                if ($leaf > 0) {
                    $total = $user->total_leaf + $leaf;
                } else {
                    $total = $user->total_leaf;
                }
                //更新会员信息
                $user->save(['gold_leaf' => $after, 'total_leaf' => $total]);
                //写入日志
                LeatLog::create(['user_id' => $user_id, 'leaf' => $leaf, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($user_id = 0)
    {
        $user = self::get($user_id);
        if ($user->total_money >= 399 && !$user->code) {
            $user->code = generate_invite_code();
        }
        if ($user->total_money >= 399 && $user->total_money < 999) {
            $user->product_level = 1;
        }
        if ($user->total_money >= 999 && $user->total_money < 9999) {
            $user->product_level = 2;
        }
        if ($user->total_money >= 9999 && $user->total_money < 99999) {
            $user->product_level = 3;
        }
        if ($user->total_money >= 99999) {
            $user->product_level = 4;
        }
        $user->save();
    }
    /**
     * 订单分佣
     * @param int $id 订单id
     * @return int
     */
    public static function commission($money, $sn, $uid)
    {
        Db::startTrans();
        try {
            $user = User::get($uid);
            if ($user) {
                $p_user = User::get($user['pid']);
                if ($p_user) {
                    //一级分佣金额
                    $first_money = bcmul($money, 0.1, 2);
                    if ($first_money > 0)
                        MoneyLog::income($p_user->id, $first_money, 0, 500, $sn);
                }
                $two_user = User::get($p_user['pid']);
                if ($two_user) {
                    //二级分佣金额
                    $two_money = bcmul($money, 0.05, 2);
                    if ($two_money > 0)
                        MoneyLog::income($two_user->id, $two_money, 0, 500, $sn);
                }
            }

            //团队分佣
            if ($user->paren_ids) {
                $ids = explode(',', $user->paren_ids);
                $users = User::whereIn('id', $ids)->where('leaf_level', '>', 1)->select();
                foreach ($users as $v) {
                    if ($v['leaf_level'] == 2) {
                        $num = User::where("pid", $v['id'])->where('leaf_level', '>', 0)->count();
                        $team_money = bcmul($money, 0.05, 2);
                        if ($num > 4 && $team_money > 0) {
                            MoneyLog::income($v->id, $team_money, 0, 501, $sn);
                        }
                    }
                    if ($v['leaf_level'] == 3) {
                        $num = User::where("pid", $v['id'])->where('leaf_level', '>', 1)->count();
                        $team_money = bcmul($money, 0.07, 2);
                        if ($num > 4 && $team_money > 0) {
                            MoneyLog::income($v->id, $team_money, 0, 501, $sn);
                        }
                    }
                    if ($v['leaf_level'] == 4) {
                        $num = User::where("pid", $v['id'])->where('leaf_level', '>', 2)->count();
                        $team_money = bcmul($money, 0.18, 2);
                        if ($num > 4 && $team_money > 0) {
                            MoneyLog::income($v->id, $team_money, 0, 501, $sn);
                        }
                    }
                    if ($v['leaf_level'] == 5) {
                        $num = User::where("pid", $v['id'])->where('leaf_level', '>', 3)->count();
                        $team_money = bcmul($money, 0.30, 2);
                        if ($num > 2 && $team_money > 0) {
                            MoneyLog::income($v->id, $team_money, 0, 501, $sn);
                        }
                    }
                }
                // foreach ($users as &$v) {
                //     $num = User::where("find_in_set({$v->id},paren_ids)")->count();
                //     $team_money = 0;
                //     if ($num >= 1000) {
                //         $team_money = bcmul($money, 0.05, 2);
                //     } elseif ($num >= 500 && $num <= 999) {
                //         $team_money = bcmul($money, 0.03, 2);
                //     } elseif ($num >= 100 && $num <= 499) {
                //         $team_money = bcmul($money, 0.02, 2);
                //     } elseif ($num >= 3 && $num <= 99) {
                //         $team_money = bcmul($money, 0.01, 2);
                //     }
                //     if ($team_money > 0) {
                //         MoneyLog::income($v->id, $team_money, 2, 501, $sn);
                //     }
                // }
            }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            return  $th->getMessage();
        }
    }

    /**
     * 金叶子订单分佣
     * @param int $id 订单id
     * @return int
     */
    public static function leafcommission($order)
    {
        Db::startTrans();
        try {
            $user = User::get($order->user_id);
            $puser = User::get($user['pid']);
            if (!$puser) {
                Db::commit();
                return true;
            }
            //推荐同等及以上级别获赠GR积分
            if ($user['leaf_level'] >= $puser['leaf_level'] && $puser['leaf_level'] > 1) {
                $money = bcmul($order->price, 0.2, 2);
                if ($money > 0) {
                    MoneyLog::income($puser['id'], $money, 0, 700, $order->sn);
                }
            }

            $total_leaf = User::sum('gold_leaf');
            if ($total_leaf < 300000) {
                $member = Member::get($order->goods_id);
                if ($total_leaf + $member->leaf > 300000) {
                    $leaf = bcsub(300000, $total_leaf, 0);
                } else {
                    $leaf = $member->leaf;
                }
                //购买金叶子团队赠送金叶子
                User::leaf($leaf, $user->id, '购买金叶子团队赠送金叶子');
            }
            //检查金叶子是否满足升级条件
            self::checkLeafUpgrade($user);
            //检查上级创客是否满足升级条件
            if ($puser && $puser['leaf_level'] > 1) {
                self::checkUpgrade($user, $puser);
            }

            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            return  $th->getMessage();
        }
    }

    public static function checkUpgrade($user, $puser)
    {
        //检查上级创客是否满足升级条件
        if ($user->leaf_level > 1 && $puser['leaf_level'] > 1) {
            $num = User::where("pid", $puser['id'])->where('leaf_level', '>', 1)->count();
            if ($num >= 10) {
                $total_leaf = User::sum('gold_leaf');
                if ($total_leaf + 1 < 300000) {
                    User::leaf(1, $puser->id, '创客推荐同等级10人赠送金叶子');
                }
                $puser->leaf_level = 3;
                $puser->save();
                //检查金叶子是否满足升级条件
                self::checkLeafUpgrade($puser);
            }
        }
    }

    public static function checkLeafUpgrade($user)
    {
        //检查金叶子是否满足升级条件
        if ($user->total_leaf >= 3 && $user->leaf_level < 4) {
            $user->leaf_level = 4;
        } else if ($user->total_leaf >= 13 && $user->leaf_level < 5) {
            $user->leaf_level = 5;
        } else if ($user->total_leaf >= 33 && $user->leaf_level < 6) {
            $user->leaf_level = 6;
        }
        $user->save();
    }
}
